package com.eclink.asset.consume.handler;


import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.alibaba.fastjson.JSON;
import com.eclink.asset.asset.domain.dao.FlowApply;
import com.eclink.asset.consume.domain.dao.ConsumeInventory;
import com.eclink.asset.consume.domain.dao.ConsumeInventoryBatch;
import com.eclink.asset.consume.domain.form.ApplyFormDataHCPF;
import com.eclink.asset.consume.service.ConsumeFileService;
import com.eclink.asset.consume.service.ConsumeInventoryService;
import com.eclink.asset.consume.service.ConsumeWarehouseService;
import com.eclink.asset.enums.ApplyStateEnum;
import com.eclink.asset.workflow.handler.ApplyFinishHandler;
import com.eclink.asset.workflow.mapper.FlowApplyMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class ConsumeApplyDispatchHandler implements ApplyFinishHandler {

    @Resource
    private FlowApplyMapper flowApplyMapper;

    @Resource
    private ConsumeInventoryService inventoryService;

    @Resource
    private ConsumeFileService fileService;

    @Resource
    private ConsumeWarehouseService consumeWarehouseService;

    @Resource
    private SnowflakeGenerator snowflakeGenerator;

    private void handleItem(ConsumeInventory item) {

        Integer num = item.getNum();
        List<ConsumeInventoryBatch> list = inventoryService.getInventoryBatchList(item.getFileId());
        for (ConsumeInventoryBatch batch : list) {
            if (batch.getNum()>num) {
                inventoryService.updateBatchNum(batch.getId(), batch.getNum()-num);
                break;
            } else {
                num = num - batch.getNum();
                inventoryService.updateBatchNum(batch.getId(), 0);
                if (num <=0) {
                    break;
                }
            }
        }

    }

    @Transactional
    public void execute(String id) {

        FlowApply flowApply = flowApplyMapper.selectById(id);
        flowApply.setUpdateTime(LocalDateTime.now());
        flowApply.setState(ApplyStateEnum.APPROVED.getValue());
        flowApplyMapper.updateById(flowApply);

        ApplyFormDataHCPF formData = JSON.parseObject(flowApply.getFormData(), ApplyFormDataHCPF.class);
        Long targetUserId = formData.getTargetUserId();
        List<ConsumeInventory> items = formData.getItems();
        for (ConsumeInventory item : items) {
            handleItem(item);

        }
    }

    @Override
    public void reject(String id) {
        FlowApply flowApply = flowApplyMapper.selectById(id);
        flowApply.setUpdateTime(LocalDateTime.now());
        flowApply.setState(ApplyStateEnum.REJECT.getValue());
        flowApplyMapper.updateById(flowApply);
    }

}
